package com.ourselec.dynamicclass;

import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Method;

import com.sun.tools.javac.Main;

public class CreateClass {
	private static String CLASS_NAME = "CreateClassTest";
	private static String CLASS_FILE = CLASS_NAME + ".java";

	public static void main(String args[]) {
		CreateClass mtc = new CreateClass();
		mtc.createClass();
		System.out.println("javac " + CLASS_FILE);
		mtc.compileClass();
		System.out.println("java " + CLASS_NAME);
		mtc.runClass();
	}

	public void createClass() {
		try {
			new File(CLASS_FILE).delete();
			FileWriter aWriter = new FileWriter(CLASS_FILE, true);
			aWriter.write("public   class   " + CLASS_NAME + "{");
			aWriter.write("public   void   println()   {");
			aWriter.write("System.out.println(\" = " + CLASS_NAME + " = \");");
			aWriter.write("}}");
			aWriter.flush();
			aWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void compileClass() {
		String filePath = new File(CreateClass.class.getClassLoader()
				.getResource("").getFile()).getAbsolutePath();
		String[] source = { "-d", filePath, new String(CLASS_FILE) };
		System.out.println("javac out:"
				+ Main.compile(source));
	}

	public void runClass() {
		try {
			Class params[] = {};
			Object paramsObj[] = {};
			Class testClass = Class.forName(CLASS_NAME);
			Object iClass = testClass.newInstance();
			Method thisMethod = testClass.getDeclaredMethod("println", params);
			thisMethod.invoke(iClass, paramsObj);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}